﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace SeguradoraIA.Framework.Business
{
    public static class HashHelper
    {
        private static readonly Dictionary<Type, IEnumerable<PropertyInfo>> propertyInfoList = new Dictionary<Type, IEnumerable<PropertyInfo>>();
        public static int GetHashCode(object obj)
        {
            return GetProperties(obj).Select(property => property.GetValue(obj, null)).Where(value => value != null).Aggregate(0, (current, value) => (current*31) ^ value.GetHashCode());
        }
        private static IEnumerable<PropertyInfo> GetProperties(object obj)
        {
            var type = obj.GetType();
            IEnumerable<PropertyInfo> propertyInfos;

            if (propertyInfoList.ContainsKey(type))
            {
                propertyInfos = propertyInfoList[type];
            }
            else
            {
                propertyInfos = type.GetProperties();
                propertyInfoList[type] = propertyInfos;
            }
            return propertyInfos;
        }
    }
}
